import java.io.*;
import java.io.IOException;
import java.net.Socket;


public class ElevatorWorker implements Runnable {
	GroupDispatcher gd;
	public Socket skt;
	int floor;
	char direction;
	int[] floorList;
	DataOutputStream outToClient;
	BufferedReader inFromClient;
	
	public ElevatorWorker(Socket skt, GroupDispatcher gd) throws IOException{
		this.skt = skt;
		this.gd = gd;
		outToClient = new DataOutputStream(skt.getOutputStream());
		inFromClient = new BufferedReader(new InputStreamReader(skt.getInputStream()));
	}
	public void run(){
		byte[] message;
		while(true){
			//wait until get a message
			try {
				message = inFromClient.readLine().getBytes();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
					
			//NOTE: STILL NEED TO FIGURE OUT HOW WE WILL PARSE MESSAGE
		
			char d = 'D'; //current direction received from message
			int f = 0; //current floor received from message
			int[] list = null; //current path list received from message
			
			
			//update floor and path
			floor = f;
			floorList = list;
			//update lists
			if(direction != d){
				if(direction == 'N'){
					gd.freeElevators.removeElement(this);
					if(d == 'U'){					
						gd.upElevators.add(this);
					}else if(d == 'D'){
						gd.downElevators.add(this);
					}else{
						System.out.println("Error: Invalid Direction Received");
						continue;
						//ERROR. Invalid direction received.
					}
				}
				else if(direction == 'U'){
					gd.upElevators.removeElement(this);
					if(d == 'D'){
						gd.downElevators.add(this);
					}else if(d == 'N'){
						gd.freeElevators.add(this);
					}else{
						System.out.println("Error: Invalid Direction Received");
						//ERROR. Invalid direction received.
					}
				}
				else if(direction == 'D'){
					gd.downElevators.removeElement(this);
					if(d == 'U'){
						gd.upElevators.add(this);
					}else if(d == 'N'){
						gd.freeElevators.add(this);
					}else{
						System.out.println("Error: Invalid Direction Received");
						//ERROR. Invalid direction received.
					}
				}else{
					System.out.println("Warning: Previous Direction Invalid..");
					//ERROR. Current Direction Invalid
				}
				direction = d;
			}	
		}
	}
	public void send(int message) throws IOException{
		outToClient.writeInt(message);
		return;
	}
	public int getFloor(){
		return floor;
	}
}
